/** @format */

var express = require('express')
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')
var { createProxyMiddleware } = require('http-proxy-middleware')
const routers = require('../src/index').default
const dbs = require('../src/db')
const { port, serverProxy } = require('./package.json')
var app = express()

app.use(cookieParser())
app.use(
  bodyParser.urlencoded({
    extended: true
  })
)
app.use(bodyParser.json())
app.get('/', (req, res) => {
  res.json({ message: `ok` })
})

// 执行本地云函数方法
app.post('/handler', async (req, res) => {
  console.log(req.body)
  let { data, openId, db } = req.body
  if (!db) {
    res.json({ message: `参数错误,缺少数据库db` })
  }
  if (!openId) {
    res.json({ message: `参数错误,缺少openId` })
  }
  try {
    let query = JSON.parse(JSON.stringify(data))
  } catch (e) {
    res.json({ message: `查询参数格式错误` })
  }
  let { handler, data: queryData } = data
  if (!handler) {
    res.json({ message: `格式错误, handler参数不能为空` })
  }
  if (!queryData) {
    res.json({ message: `格式错误, data参数不能为空` })
  }
  if (!process.db) {
    process.db = db
  }
  req.context = {
    openId,
    db,
    env: 'mock',
    data: queryData,
    handler
  }
  if (routers[handler]) {
    let result = await routers[handler](req.context)
    res.json(result)
  } else {
    res.json({ message: `函数${handler}不存在` })
  }
})

// 获取本地export的数据库表及云函数
app.get('/getDBHandlers', async (req, res) => {
  let handlers = routers

  // dbsInfo
  let dbArray = []
  let handlerArray = []
  Object.keys(dbs).map(v => {
    dbArray.push(dbs[v])
  })
  Object.keys(handlers).map(v => {
    handlerArray.push(v)
  })
  console.log(dbArray, handlerArray)
  res.json({
    dbs: dbArray,
    handlers: handlerArray,
    success: true
  })
})

const ProxyOption = {
  target: serverProxy.target,
  changeOrigin: true,
  pathRewrite: (path, req) => {
    console.log(`path`, path)
    return path.replace('/proxy', '')
  },
  onProxyReq: (proxyReq, req, res) => {
    console.log(`req.body`, req.body)
    if (req.body) {
      let bodyData = JSON.stringify(req.body)
      console.log(`bodyData`, bodyData)
      // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
      proxyReq.setHeader('Content-Type', 'application/json')
      proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
      // stream the content
      proxyReq.write(bodyData)
    }
  }
}

app.use('/proxy', createProxyMiddleware(ProxyOption))

app.listen(port || 5555)
